package com.linghang.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linghang.demo.domain.Production;
import com.linghang.demo.domain.ProductionExample;
import com.linghang.demo.mapper.ProductionMapper;
import com.linghang.demo.req.ProductionQueryReq;
import com.linghang.demo.req.ProductionSaveReq;
import com.linghang.demo.resp.PageResp;
import com.linghang.demo.resp.ProductionQueryResp;
import com.linghang.demo.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ProductionService {
    private int id=10;
    @Resource
    private ProductionMapper productionMapper;
    private static final Logger LOG = LoggerFactory.getLogger(ProductionService.class);

    public List<Production> list(){
        return productionMapper.selectByExample(null);
    }

    public PageResp<ProductionQueryResp> list(ProductionQueryReq req) {
        ProductionExample productionExample = new ProductionExample();
        ProductionExample.Criteria criteria = productionExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getId())) {
            criteria.andIdEqualTo(  req.getId() );
        }

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Production> productionList = productionMapper.selectByExample(productionExample);

        PageInfo<Production> pageInfo = new PageInfo<>(productionList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // List<ProductionResp> respList = new ArrayList<>();
        // for (Production production : productionList) {
        //     // ProductionResp productionResp = new ProductionResp();
        //     // BeanUtils.copyProperties(production, productionResp);
        //     // 对象复制
        //     ProductionResp productionResp = CopyUtil.copy(production, ProductionResp.class);
        //
        //     respList.add(productionResp);
        // }

        // 列表复制
        List<ProductionQueryResp> list = CopyUtil.copyList(productionList, ProductionQueryResp.class);

        PageResp<ProductionQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;
    }

    /**
     * 保存
     */
    public void save(ProductionSaveReq req) {
        Production production = CopyUtil.copy(req, Production.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            production.setId(id++);
            productionMapper.insert(production);

        } else {
            // 更新
            productionMapper.updateByPrimaryKey(production);

        }
    }

    
    public void  delete(int id){
        productionMapper.deleteByPrimaryKey(id);
    }
}
